package com.weixing.mall.core.converter;

import com.weixing.mall.base.enums.IBaseEnum;
import com.weixing.mall.base.utils.EnumUtil;
import org.springframework.core.convert.converter.Converter;
import org.springframework.core.convert.converter.ConverterFactory;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

/**
 * String 参数类型转枚举
 */

@Component
public class EnumConvertFactory implements ConverterFactory<String , IBaseEnum> {
    @Override
    public <T extends IBaseEnum> Converter<String, T> getConverter(Class<T> targetType) {
        return new StringToIEum<>(targetType);
    }

    @SuppressWarnings("all")
    private static class StringToIEum<T extends IBaseEnum> implements Converter<String, T> {
        private Class<T> targerType;

        public StringToIEum(Class<T> targerType) {
            this.targerType = targerType;
        }

        @Override
        public T convert(String source) {
            if (StringUtils.isEmpty(source)) {
                return null;
            }
//            return (T) EnumConvertFactory.getIEnum(this.targerType, source);
            return EnumUtil.getIEnum(this.targerType, source);
        }
    }
}